/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("Fk_reim",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using VOL.Entity.DomainModels;
using VOL.MyTable.IServices;
using Microsoft.AspNetCore.Authorization;
using VOL.Core.ManageUser;
using VOL.MyTable.IRepositories;
using VOL.MyTable.Repositories;
using System.Linq;
using VOL.Core.Utilities;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using VOL.Core.DBManager;
using VOL.System.IRepositories;
using Microsoft.EntityFrameworkCore;
using VOL.System.Repositories;
using VOL.MyTable.Services;
using System.Collections;
using VOL.WebApi.Controllers.MyTable;
using VOL.Core.Filters;

namespace VOL.MyTable.Controllers
{
    public partial class Fk_reimController
    {
        private readonly IFk_reimService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;
        private ISys_UserRoleRepository _userRepository;
        [ActivatorUtilitiesConstructor]
        public Fk_reimController(
            IFk_reimService service,
            IHttpContextAccessor httpContextAccessor,
            ISys_UserRoleRepository userRepository
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
            _userRepository = userRepository;
        }


        /// <summary>
        /// 获取案件所有登录的审理意见
        /// </summary>
        /// <param name="reimid"></param>
        /// <returns></returns>
        [HttpPost, Route("get_reimfloat"), AllowAnonymous]
        public object get_reimfloat(int reimid)
        {

            Hashtable rtn_hst = new Hashtable();
            string[] array_notetype = { "sqj_ok", "sqj" };//两种审批类型，sqj申请状态，sqj_ok申请同意
                IQueryable<Fk_reimfloat> query_f = Fk_reimfloatRepository.Instance.FindAsIQueryable(x => (x.reimid == reimid && array_notetype.Contains(x.node_type)));
                List<Fk_reimfloat> listFk_reimfloat = query_f.ToList();

           
            rtn_hst.Add("rf_list", listFk_reimfloat);
            
            return rtn_hst;
           
        }

        /// <summary>
        /// 获取当前登录的审理意见，stepid,remid,能确定唯一条记录,并且检查票号是否重复填写
        /// </summary>
        /// <param name="reimid"></param>
        /// <returns></returns>
        [HttpPost, Route("get_curr_reimfloat"), AllowAnonymous]
        public object get_curr_reimfloat(int reimid )
        {
            Hashtable rtn_hst = new Hashtable();
            string loginid = UserContext.Current.GetUserInfo(UserContext.Current.UserId).UserName;
            IQueryable<Fk_reim> query = Fk_reimRepository.Instance.FindAsIQueryable(x => x.reim_id == reimid);
            List<Fk_reim> listreim = query.ToList();
            if (listreim.Count > 0)
            {
               Fk_reim cur_Fk_reim = listreim[0];
                
               IQueryable<Fk_reimfloat> query_f = Fk_reimfloatRepository.Instance.FindAsIQueryable(x => (x.reimid == reimid && x.stepid==cur_Fk_reim.stepid && x.node_type== "key"));
               List<Fk_reimfloat> listFk_reimfloat = query_f.ToList();
               if (listFk_reimfloat.Count > 0)
                {
                    Fk_reimfloat cur_Fk_reimfloat = listFk_reimfloat[0];
                    rtn_hst.Add("reimfloat", cur_Fk_reimfloat);
                    //return cur_Fk_reimfloat;
                }
                //检查是否重复填写,>=1表示票号有重复,排除了自己只有>=1说明之前重复的票号
                string[] array_tinckno = Fk_reimlistRepository.Instance.FindAsIQueryable(x => x.reim_id == reimid).Select(s => s.tickno.Trim()).ToArray();
                List<Fk_reimlist> rl_list = Fk_reimlistRepository.Instance.FindAsIQueryable(x => array_tinckno.Contains(x.tickno) && x.reim_id!=reimid).ToList();
               // rl_list.Count();
                rtn_hst.Add("tickno_rows", rl_list.Count());
            }
            return rtn_hst;
            // query.
            //rtnobj
            //IQueryable<Fk_reim> queryeable = repository.DbContext.Set<Fk_reim>();  
        }

        [HttpPost, Route("update_curr_reimfloat"), AllowAnonymous]
        public IActionResult update_curr_reimfloat([FromBody] Fk_reimfloat ff)
        {
            WebResponseContent webResponse = new WebResponseContent();
            /*var jsonStr = JsonConvert.SerializeObject(jsonobj);//序列化为json字符串
            var jsonParam = JsonConvert.DeserializeObject<dynamic>(jsonStr);//反序列化为动态json对象

            int fk_reimfloat_id = jsonParam.fk_reimfloat_id;
            string remark = jsonParam.remark;*/

            IFk_reimfloatRepository repository = Fk_reimfloatRepository.Instance;
            // Fk_reimfloat ff =new Fk_reimfloat();
            // ff.fk_reimfloat_id = fk_reimfloat_id;
            //ff.remark = remark;
            //repository.Update(ff,true);
            string loginid = UserContext.Current.GetUserInfo(UserContext.Current.UserId).UserName;
            ff.username = loginid;
            ff.bdatetime = DateTime.Now;
            repository.Update(ff, x => new { x.fk_reimfloat_id, x.remark,x.bdatetime,x.username },true);//只更新相关字段

            return Json(webResponse.OK("保存成功"));
            //return webResponse.OK("保存成功");
        }

        /// <summary>
        /// 获取当前步骤的下一步骤号
        /// </summary>
        /// <param name="reimid">当前业务号</param>
        /// <param name="current_stepid">当前步骤号</param>
        /// <returns>-1表示没有归档</returns>
        [HttpPost, Route("get_next_step"), AllowAnonymous]
        public int get_next_step(int reimid, int current_stepid)
        {
            /*int? rtn =0;
            IQueryable<Fk_reimfloat> sf_queryeable = Fk_reimfloatRepository.
                Instance.FindAsIQueryable(t => (t.reimid == reimid) && (t.stepid == current_stepid) && (t.node_type == "key"));
            rtn = sf_queryeable.Select(t => t.nextstepid).FirstOrDefault();
            return rtn;*/
            return (int)wfoa_tools.get_next_step(reimid,current_stepid);
        }

        /// <summary>
        /// 获取stepid对应的处理人，需要登录才能测试
        /// </summary>
        /// <param name="reimid">当前业务号</param>
        /// <param name="stepid">当前步骤号</param>
        /// <returns></returns>
        [HttpPost, Route("get_next_ren"), AllowAnonymous]
        public string get_next_ren(int reimid, int stepid)
        {
            if (stepid == 9) return "";//如果是归档直接返回空

            IQueryable<Fk_reimfloat> ls_reimfloat_key = Fk_reimfloatRepository.
               Instance.FindAsIQueryable(t => (t.reimid == reimid) && (t.stepid == 1) && (t.node_type == "key"));
            string ls_username = ls_reimfloat_key.FirstOrDefault().username;//获取案件起草人

            Fk_reimfloat fkrfloat = new Fk_reimfloat();
            IQueryable<Fk_reimfloat> sf_queryeable = Fk_reimfloatRepository.
                Instance.FindAsIQueryable(t => (t.reimid == reimid) && (t.stepid == stepid));
            fkrfloat = sf_queryeable.FirstOrDefault();
            if(fkrfloat.roleid==25)//25表示上一级领导角色
            {
                //return  this.get_manager_username(UserContext.Current.GetUserInfo(UserContext.Current.UserId).UserName);
                return this.get_manager_username(ls_username);//上一级领导表示的是当前起草人的上一级领导
            }
            if (fkrfloat.roleid == 20)//20表示本部门经理角色
            {
                //string[] username_arr =this.get_oayi_mg_dfrom_userid(UserContext.Current.GetUserInfo(UserContext.Current.UserId).UserName);
                string[] username_arr = this.get_oayi_mg_dfrom_userid(ls_username);
                return string.Join(",", username_arr);//把字符串数组用逗号,连接 
            }
            if (fkrfloat.roleid == 36)//36表示主控部门经理角色
            {
                //string[] username_arr =this.get_oayi_mg_dfrom_userid(UserContext.Current.GetUserInfo(UserContext.Current.UserId).UserName);
                string tsql = fkrfloat.tjsql;
                tsql = tsql.Replace("@reim_id@", reimid.ToString());
                List<dynamic> rnt_list = DBServerProvider.SqlDapper.QueryList<dynamic>(tsql, "").ToList();
                if (rnt_list.Count > 0)
                {
                    return wfoa_tools.get_bmfzr_from_depidoa((int)rnt_list[0].zk_depid);//主控部门责任人
                }
                return "";
               // return string.Join(",", username_arr);//把字符串数组用逗号,连接 
            }
            if (fkrfloat.roleid == 21)//21表示分管领导，根据起草人找到分管领导
            {        
                return wfoa_tools.get_ggld_from_userid(ls_username);
                // return string.Join(",", username_arr);//把字符串数组用逗号,连接 
            }
            else//如果是其他的角色，就找到角色对应的username
            {
                /* IQueryable<Sys_UserRole> Sys_UserRole_q = Sys_UserRoleRepository.
                 Instance.FindAsIQueryable(t => (t.RoleId == fkrfloat.nextroleid));
                 int[] usernames=Sys_UserRole_q.Select(t=>t.UserId).ToArray();
                 string[] usernamesarry = (from a in DBServerProvider.DbContext.Set<Sys_User>()
                                           join b in DBServerProvider.DbContext.Set<Sys_UserRole>()
                                           on a.User_Id equals b.UserId
                                           where b.RoleId == fkrfloat.nextroleid
                                           select*/
                int ?ls_roleid = fkrfloat.roleid;
                string sqlstr = $"select a.UserName from sys_user a,sys_userrole b where a.User_Id=b.UserId and b.RoleId=@ls_roleid";
                string []username_arr=DBServerProvider.SqlDapper.QueryList<string>(sqlstr, new { ls_roleid }).ToArray();
                return string.Join(",", username_arr);//把字符串数组用逗号,连接
            }
    
        }

        /// <summary>
        /// 获取起草人,loginid
        /// </summary>
        /// <param name="_reimid">当前业务号</param>
        /// <returns>0表示没有下一步骤</returns>
        [HttpPost, Route("get_qc_ren"), AllowAnonymous]
        public string get_qc_ren(int _reimid)
        {
            //string rnt = "";
            string sqlstr = $"select username from fk_reimfloat where reimid=@_reimid and node_type='key' and username!='' and  stepid=1";
            string username_arr = DBServerProvider.SqlDapper.QueryList<string>(sqlstr, new { _reimid }).FirstOrDefault();
            return username_arr;
        }
        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="reimid">当前业务号</param>
        /// <param name="current_stepid">当前步骤号</param>
        /// <param name="tp">pre=提交，back=回退</param>
        ///  <param name="pdata">树形选择接受人（汇签人）</param>
        /// <param name="ff">审理意见</param>
        /// <returns></returns>
        [HttpPost, Route("up_tijiao"), AllowAnonymous]
        public IActionResult up_tijiao(int reimid, int current_stepid,string tp,string pdata,[FromBody] Fk_reimfloat ff)
        {
            WebResponseContent webResponse = new WebResponseContent();
            int nextstepid=0;
            string nextusername="";
            string tousername = "";//从前端传来的汇签人
            string rntstr = "";
            dynamic queryJson = JsonConvert.DeserializeObject(pdata);//树形选择接受人,汇签人
            //Console.WriteLine(queryJson);
            string loginid = UserContext.Current.GetUserInfo(UserContext.Current.UserId).UserName;
            IQueryable<Fk_reim> ls_reim = Fk_reimRepository.
                 Instance.FindAsIQueryable(t => (t.reim_id == reimid));
            //string step_username = ls_reim.FirstOrDefault().hq_username;//接受人
            string hq_username = ls_reim.FirstOrDefault().hq_username;//汇签人

            if (tp == "back")
            {  
                nextstepid = 1;
                hq_username = "";
                nextusername = get_qc_ren(reimid);//回退到起草人
                weixin_tools.SendTempletMessge_dcl(nextusername, "驳回业务编号为：" + reimid.ToString());
                rntstr = "回退成功";
                tp = "back";
            }
            if (tp == "pre")
            {
                foreach (dynamic item in queryJson)
                {
                    //weixin_tools.SendTempletMessge_dcl(item.username.ToString(),"待处理业务编号为：" + reimid.ToString());
                    if (item.username != "") tousername = tousername + "," + item.username;
                }
                if (!string.IsNullOrEmpty(tousername))//说明汇签人员不为空，删除自己后存入
                {
                    if (tousername.Substring(0, 1) == ",")
                    {
                        tousername = tousername.Substring(1);//去掉,逗号
                    }
                }
                // if(!string.IsNullOrEmpty(tousername)) 
                hq_username = hq_username + "," + tousername;
                if (!string.IsNullOrEmpty(hq_username))//说明汇签人员不为空，删除自己后存入
                {    
                    
                    if (hq_username.Substring(0, 1) == ",")
                    {
                        hq_username = hq_username.Substring(1);//去掉,逗号
                    }
                    hq_username = CustomHelper.del_rep_str_dou(hq_username);//去掉重复名称
                    hq_username = CustomHelper.del_string_dou(hq_username, loginid);//不包括自己

                    if (hq_username.Length > 0)//
                    {
                        tp = "hq";//汇签
                        nextusername = "";
                        nextstepid = (int)ls_reim.FirstOrDefault().stepid;//不变
                        for (int i = 0; i <= hq_username.Split(",").Length - 1; i++)
                        {
                            weixin_tools.SendTempletMessge_dcl(hq_username.Split(",")[i].ToString(), "待处理业务编号为：" + reimid.ToString());
                        }
                        rntstr = "提交成功";
                    }
                    else//如果所有汇签人全部处理后，提交到下一步
                    {
                        tp = "pre";//汇签
                        nextstepid = this.get_next_step(reimid, current_stepid);
                        nextusername = this.get_next_ren(reimid, nextstepid);//获取固定节点接受人
                        for (int i = 0; i <= nextusername.Split(",").Length - 1; i++)
                        {
                            weixin_tools.SendTempletMessge_dcl(nextusername.Split(",")[i].ToString(), "待处理业务编号为：" + reimid.ToString());
                        }
                        rntstr = "提交成功";
                    }
                    
                }
                else//正常流程提交
                {
                    hq_username = "";
                    nextstepid = this.get_next_step(reimid, current_stepid);
                    nextusername = this.get_next_ren(reimid, nextstepid);//获取固定节点接受人
                    tp = "pre";
                    for (int i = 0; i <= hq_username.Split(",").Length - 1; i++)
                    {
                        weixin_tools.SendTempletMessge_dcl(nextusername.Split(",")[i].ToString(), "待处理业务编号为：" + reimid.ToString());
                    }
                    rntstr = "提交成功";
                }
            }

            //插入提交或回退记录到float表
            IFk_reimfloatRepository rf_repository = Fk_reimfloatRepository.Instance;
            Fk_reimfloat fkrfloat = new Fk_reimfloat();
            Fk_reimfloat add_float = new Fk_reimfloat();
            IQueryable<Fk_reimfloat> sf_queryeable = Fk_reimfloatRepository.
                Instance.FindAsIQueryable(t => (t.reimid == reimid));
            fkrfloat = sf_queryeable.FirstOrDefault();
           
            add_float.typeid = fkrfloat.typeid;
            add_float.username = loginid;
            add_float.bdatetime = DateTime.Now;
            add_float.remark = ff.remark;
            add_float.reyijian = ff.reyijian;   
            add_float.reimid = fkrfloat.reimid;
            add_float.stepid = current_stepid;
            add_float.nextstepid = nextstepid;
            add_float.node_type = tp;//提交类型的操作
            add_float.next_username = nextusername;
            rf_repository.Add(add_float,true);


            IFk_reimRepository repository = Fk_reimRepository.Instance;
            Fk_reim fkr = new Fk_reim();
            fkr.reim_id = reimid;
            fkr.stepid = nextstepid;
            fkr.step_username = nextusername;
            fkr.hq_username = hq_username;
            repository.Update(fkr, t => new { t.stepid, t.step_username,t.hq_username }, true);//更新Fk_reim部分数据

            return Json(webResponse.OK(rntstr));
        }
        /// <summary>详情见PPT
        /// Fk_reim-nextusername：下一步骤处理人提交逻辑：        ///    1、在同一节点中协同处理人需全部处理完毕才可以提交到下一环节；        ///    2、同时协作人员也可以选择其他协作人员；
        /// </summary>
        /// <param name="step_username">提交前</param>
        /// <param name="touser">前台界面选择</param>
        /// <param name="gd_username">流程中节点固定接受人</param>
        /// <returns>协同处理人员</returns>
  /*      private string get_xt_username(string step_username, string touser, string gd_username)
        {
            string xt_username = "";
            xt_username = step_username + "," + touser;
            string[] dg_arr = gd_username.Split(",");
            for (int i = 0; i < dg_arr.Length; i++)
            {
                xt_username = CustomHelper.del_string_dou(xt_username, dg_arr[i]);
            }
            return CustomHelper.del_rep_str_dou(xt_username);
        }*/

        /// <summary>
        /// 获取上一步骤号
        /// </summary>
        /// <param name="reimid">当前业务号</param>
        /// <param name="current_stepid">当前步骤号</param>
        /// <returns>0表示没有上一步骤</returns>
        [HttpPost, Route("get_pre_step"), AllowAnonymous]
        public int? get_pre_step(int reimid, int current_stepid)
        {
            int? rtn = 0;
            IQueryable<Fk_reimfloat> sf_queryeable = Fk_reimfloatRepository.
                  Instance.FindAsIQueryable(t => (t.reimid == reimid) && (t.nextstepid == current_stepid) && (t.node_type == "key"));
            rtn = sf_queryeable.Select(t => t.stepid).FirstOrDefault();
            return rtn;
        }

        /// <summary>
        /// 获取上一步骤处理人
        /// </summary>
        /// <param name="reimid">当前业务号</param>
        /// <param name="current_stepid">当前步骤号</param>
        /// <returns>""</returns>
        [HttpPost, Route("get_pre_username"), AllowAnonymous]
        public string get_pre_username(int reimid, int current_stepid)
        {
            string pre_username = "";
            IQueryable<Fk_reimfloat> sf_queryeable = Fk_reimfloatRepository.
                  Instance.FindAsIQueryable(t => (t.reimid == reimid) && (t.nextstepid == current_stepid) && (t.node_type == "key"));
            pre_username = sf_queryeable.Select(t => t.username).FirstOrDefault();
            return pre_username;
        }
        /// <summary>
        /// 获取自己的直接领导username,通过OA的中逻辑关系,
        /// </summary>
        /// <param name="username"></param>
        /// <returns></returns>
        [HttpPost, Route("get_manager_username"), AllowAnonymous]
        public string get_manager_username(string username)
        {
            return wfoa_tools.get_manager_username(username);
        }

        /// <summary>
        /// 保存用户角色
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("saveUserRole")]
        //public async Task<IActionResult> SaveRole([FromBody] int[] roleIds, int userId)
        public IActionResult saveUserRole([FromBody] int[] roleIds, int userId)
        {
            WebResponseContent _webResponse = new WebResponseContent();
           // Console.WriteLine(roleIds.ToString());
            if (roleIds == null || userId <= 0)
            {
                return Json(_webResponse.OK("未获取到参数"));
            }

           //如果需要判断当前角色是否越权，再调用一下获取当前角色下的所有子角色判断即可

            var roles = _userRepository.FindAsIQueryable(x => x.UserId == userId)
              .Select(s => new { s.RoleId, s.Enable, s.Id,s.UserId })
              .ToList();
            //没有设置角色
            if (roleIds.Length == 0 && roles.Exists(x => x.Enable == 1))
            {
                return Json(_webResponse.OK("保存成功"));
            }
            
           UserInfo user = UserContext.Current.UserInfo;

           var del= roles.Where(x => x.UserId== userId).Select(s => new Sys_UserRole()
           {
               Id = s.Id,
               Enable = 0,
               ModifyDate = DateTime.Now,
               Modifier = user.UserTrueName,
               ModifyID = user.User_Id
           }).ToList();
            if (del.Count > 0)
            {
                DBServerProvider.SqlDapper.ExcuteNonQuery("delete from Sys_UserRole where userid in(@userId)", new { userId });
            }
            
            //_userRepository.DeleteWithKeys(del);
           //新设置的角色 
           var add = roleIds.Select(s => new Sys_UserRole()
           {
               RoleId = s,
               UserId = userId,
               Enable = 1,
               CreateDate = DateTime.Now,
               Creator = user.UserTrueName,
               CreateID = user.User_Id
           }).ToList();
           _userRepository.AddRange(add);//添加实现了ICollection接口的一个集合的所有元素到指定集合的末尾
           _userRepository.SaveChanges();
            /*
                       //删除的角色 
                       var update = roles.Where(x => !roleIds.Contains(x.RoleId) && x.Enable == 1).Select(s => new Sys_UserRole()
                       {
                           Id = s.Id,
                           Enable = 0,
                           ModifyDate = DateTime.Now,
                           Modifier = user.UserTrueName,
                           ModifyID = user.User_Id
                       }).ToList();

                       //之前设置过的角色重新分配 
                       update.AddRange(roles.Where(x => roleIds.Contains(x.RoleId) && x.Enable != 1).Select(s => new Sys_UserRole()
                       {
                           Id = s.Id,
                           Enable = 1,
                           ModifyDate = DateTime.Now,
                           Modifier = user.UserTrueName,
                           ModifyID = user.User_Id
                       }).ToList());
                       _userRepository.AddRange(add);

                       _userRepository.UpdateRange(update, x => new { x.Enable, x.ModifyDate, x.Modifier, x.ModifyID });
                       await _userRepository.SaveChangesAsync();*/
            return Json(_webResponse.OK("保存成功"));
        }

        /// <summary>
        /// 用户管理设置角色(获取所有角色)2020.11.28
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("getUserRoles")]
        public async Task<IActionResult> GetUserRoles(int userId)
        {
            var roles = await _userRepository.FindAsIQueryable(x => x.UserId == userId && x.Enable == 1)
              .Select(s => s.RoleId)
              .ToListAsync();
            return Json(roles);
        }


        /// <summary>
        /// 根据登录用户，获取该用户的一级部门的负责人，可能会出现多个领导，需要手工选
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("get_oayi_mg_dfrom_userid"), AllowAnonymous]
        public string[] get_oayi_mg_dfrom_userid(string userId)
        {
            return wfoa_tools.get_oayi_mg_dfrom_userid(userId);
        }

        /// <summary>
        /// 获取一级部门的，加载给tree,
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("get_oayi_dep_frotree"), AllowAnonymous]
        public object get_oayi_dep_frotree(int? note_type,int ?subcompanyid,int? pdepid)
        {

            Hashtable rtn_hst = new Hashtable();

            //Ren_oa ren = new Ren_oa();
            fk_depart depart = new fk_depart();
            Fk_subcompany subcompany = new Fk_subcompany();
           // IQueryable<fk_depart> sf_queryeable;
            IQueryable<Fk_subcompany> subcompany_queryeable;
           // Console.WriteLine(depid);
            if (note_type == -1)//加载公司节点
            {
                subcompany_queryeable = DBServerProvider.DbContext.Set<Fk_subcompany>();//获取全部数据
                rtn_hst.Add("subcomp", subcompany_queryeable.ToArray());
                
            }
            
            if (note_type == 0)//加载一级部门
            {
                string sql = "select depid_oa,depname_oa,(select count(*) from fk_depart b where b.supdepid_oa=a.depid_oa ) child_count from fk_depart a where a.supdepid_oa=0 and subcompanyid1_oa=@subcompanyid";
                dynamic[] yi_depart = DBServerProvider.SqlDapper.QueryList<object>(sql, new { subcompanyid }).ToArray();
                rtn_hst.Add("yi_depart", yi_depart);
                
            }
            if (note_type == 1)//加载普通部门
            {
                string sql = "select depid_oa,depname_oa,(select count(*) from fk_depart b where b.supdepid_oa=a.depid_oa ) child_count from fk_depart a where a.supdepid_oa=@pdepid";
                dynamic[] gen_depart = DBServerProvider.SqlDapper.QueryList<object>(sql, new { pdepid }).ToArray();//动态SQL语句，要有dynamic类型来取数比较方便
                foreach(var item in gen_depart)
                {
                   // Console.WriteLine(item.depname_oa);
                }
                rtn_hst.Add("gen_depart", gen_depart); 
            }
            IQueryable<Sys_User> sys_user_queryeable = Sys_UserRepository.Instance.FindAsIQueryable(t => (t.Dept_Id == pdepid));
            rtn_hst.Add("puser", sys_user_queryeable);
            return rtn_hst;
            //return sf_queryeable.ToArray();
            //rntmg_name = sf_queryeable.Select(s => s.LOGINID).ToArray();//当前部门oaid对应的部门长

        }


        /// <summary>
        /// 根据成本中心找到对应的费用科目
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("get_fei_for_cntr"), AllowAnonymous]
        public object get_fei_for_cntr(string rcntr)
        {

            Hashtable rtn_hst = new Hashtable();

            IQueryable<Fei_typelist> _km_query = Fei_typelistRepository.//科目
              Instance.FindAsIQueryable(t => (t.company_oa_id == 9000));//9000和8000的科目是一样的

            IQueryable<Fk_yusuan> q_Fk_yusuan = Fk_yusuanRepository.Instance.FindAsIQueryable(t => (true));

            IQueryable<rtn_strut> rtn_hst_q = from q1 in q_Fk_yusuan
                                              from q2 in _km_query
                                              where q1.rcntr == rcntr && q1.racct == q2.racct
                                              select new rtn_strut {
                                                  key=q1.racct,
                                                  value=q2.fei_typename
                                              };                                                ;

            rtn_hst.Add("rtn_hst_q", rtn_hst_q);
            return rtn_hst;
        }

        /// <summary>
        /// 点击节点获取部门人员,
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("get_renfordep"), AllowAnonymous]
        public object get_renfordep(int? pdepid)
        {
           
            Hashtable rtn_hst = new Hashtable();
            List<string> userlist_queryeable = Ren_oaRepository.Instance.FindAsIQueryable(t => (t.DEPARTMENTID == pdepid) && (t.STATUS == 1)).Select(t=>t.LOGINID).ToList();//过滤辞职的人
            IQueryable<Sys_User> sys_user_queryeable = Sys_UserRepository.Instance.FindAsIQueryable(t => (t.Dept_Id == pdepid) && userlist_queryeable.Contains(t.UserName));
            rtn_hst.Add("puser", sys_user_queryeable);
            return rtn_hst;
        }

        /// <summary>
        /// 新增待处理逻辑，考虑到兼容小程序发布
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("get_dclcount_new"), AllowAnonymous]
        public object get_dclcount_new()
        { 
           
            List<Hashtable> rtnlist = new List<Hashtable>();
            //int rntc = 0;
            string username= UserContext.Current.GetUserInfo(UserContext.Current.UserId).UserName;
            IQueryable<Fk_reim> Fk_reimqueryeable = Fk_reimRepository.Instance.FindAsIQueryable(x => x.hq_username.Contains(UserContext.Current.UserName) || ((x.hq_username == null || x.hq_username == "") && x.step_username.Contains(UserContext.Current.UserName)) && (x.typeid==1));
            if (Fk_reimqueryeable.Count() > 0)
            {
                Hashtable rtn_hst = new Hashtable();
                rtn_hst.Add("cnname", "费用报销业务待处理（"+ Fk_reimqueryeable.Count() + "）");
                rtn_hst.Add("count", Fk_reimqueryeable.Count());
                rtn_hst.Add("url", "/fk_reim");
                rtn_hst.Add("lstype", "1");//费用
                rtnlist.Add(rtn_hst);
            }
            IQueryable<Fk_reim> Fk_reimqueryeable_cl = Fk_reimRepository.Instance.FindAsIQueryable(x => x.hq_username.Contains(UserContext.Current.UserName) || ((x.hq_username == null || x.hq_username == "") && x.step_username.Contains(UserContext.Current.UserName)) && (x.typeid == 2));
            if (Fk_reimqueryeable_cl.Count() > 0)
            {
                Hashtable rtn_hst = new Hashtable();
                rtn_hst.Add("cnname", "差旅报销业务待处理（" + Fk_reimqueryeable_cl.Count() + "）");
                rtn_hst.Add("count", Fk_reimqueryeable_cl.Count());
                rtn_hst.Add("url", "/Fk_reim_cc");
                rtn_hst.Add("lstype", "2");//差旅
                rtnlist.Add(rtn_hst);
            }
            return rtnlist;
        }

        [HttpPost, Route("get_dclcount"), AllowAnonymous]
        public object get_dclcount()
        {
            //int rntc = 0;
            string username = UserContext.Current.GetUserInfo(UserContext.Current.UserId).UserName;
            IQueryable<Fk_reim> Fk_reimqueryeable = Fk_reimRepository.Instance.FindAsIQueryable(t => (t.step_username.Contains(username)));
            return Fk_reimqueryeable.Count();
        }

        /// <summary>
        /// 获取流程基础数据和固定提交人
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("get_reimfloat_data"), AllowAnonymous]
        public object get_reimfloat_data(int reim_id)
        {
            Hashtable rtn_hst = new Hashtable();

            string sql = "select fk_reimfloat_id, stepid,(select stepname from sys_step where stepid = fk_reimfloat.stepid) stepname,bdatetime bdatetime,isnull(remark,'') remark,(select usertruename from sys_user where username=fk_reimfloat.username) usertruename from fk_reimfloat where reimid = @reim_id and node_type = 'key' order by pxm desc";
            dynamic[] fk_reimfloat = DBServerProvider.SqlDapper.QueryList<object>(sql, new { reim_id }).ToArray();
            rtn_hst.Add("fk_reimfloat", fk_reimfloat);

            /*sql = "select fk_reimfloat_id, stepid,(select stepname from sys_step where stepid = fk_reimfloat.stepid) stepname,bdatetime from fk_reimfloat where reimid = @reim_id and node_type = 'key'";
            object[] fk_reimfloat = DBServerProvider.SqlDapper.QueryList<object>(sql, new { reim_id }).ToArray();
            rtn_hst.Add("gen_depart", fk_reimfloat);*/

            IQueryable<Fk_reim> reim_queryeable = Fk_reimRepository.
               Instance.FindAsIQueryable(t => (t.reim_id == reim_id));
            int ?currstepid=reim_queryeable.Select(s => s.stepid).FirstOrDefault();
            if (currstepid != 9)
            {
                string username_strarray = this.get_next_ren(reim_id, this.get_next_step(reim_id, (int)currstepid));

                IQueryable<Sys_User> Sys_User_queryeable = Sys_UserRepository.
                   Instance.FindAsIQueryable(t => (username_strarray.Contains(t.UserName)));
                Sys_User[] next_ren = Sys_User_queryeable.ToArray();
                rtn_hst.Add("next_ren", next_ren);
            }
            else
            {
                rtn_hst.Add("next_ren", "");
            }
           

            return rtn_hst;
        }




        /*/// <summary>
        /// 根据登录用户，获取该用户的一级部门ID
        /// </summary>
        /// <returns></returns>
        [HttpPost, Route("get_oayidepidfrom_userid"), AllowAnonymous]
        public int ? get_oayidepidfrom_userid(string userId)
        {
           // int rntdepid = 0;
            Ren_oa ren = new Ren_oa();
            fk_depart depart = new fk_depart();
            IQueryable<Ren_oa> sf_queryeable = Ren_oaRepository.Instance.FindAsIQueryable(t => (t.LOGINID == userId));

            int? currdepartid = decimal.ToInt32(sf_queryeable.Select(s => s.DEPARTMENTID).FirstOrDefault());//当前部门oaid

            int? yijdepid = currdepartid;
            while(yijdepid!=0)
            {
                IQueryable<fk_depart> depart_queryeable = fk_departRepository.Instance.FindAsIQueryable(t => (t.depid_oa == yijdepid));
                int ?suppdepid= depart_queryeable.Select(t => t.supdepid_oa).FirstOrDefault();
                if (suppdepid==0)
                {
                    break;
                }
                else
                {
                    yijdepid = suppdepid;
                }

            }

            return yijdepid;
        }*/


        /*[HttpPost, Route("Update"), AllowAnonymous]
        public override ActionResult Update([FromBody] SaveModel saveModel)
        {
            return base.Update(saveModel);
        }*/
    }

    class rtn_strut
    {
       public string key { get; set; }
       public string value { get; set; }
    }
}
